package com.briup.cms.service.impl;

import com.briup.cms.bean.Article;
import com.briup.cms.bean.Comment;
import com.briup.cms.dao.ArticleDao;
import com.briup.cms.dao.CommentDao;
import com.briup.cms.exception.ServiceException;
import com.briup.cms.service.ArticleService;
import com.briup.cms.util.ResultCode;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Resource
    ArticleDao articleDao;
    @Resource
    CommentDao commentDao;

    //发布资讯或者编辑资讯
    @Override
    public void saveOrUpdateArticle(Article article) throws ServiceException {

        articleDao.save(article);
    }

    //分页获取所有资讯
    //pageNum:页码，pageSize：一页显示多少条数据
    @Override
    public Page<Article> findAll(Integer pageNum, Integer pageSize) throws ServiceException {
        PageRequest pageRequest = PageRequest.of(pageNum, pageSize);
        return articleDao.findAll(pageRequest);
    }

    //批量删除资讯
    @Override
    public void deleteArticleInBatch(List<Long> ids) throws ServiceException {
        for (Long id:ids){
            articleDao.deleteById(id);
        }
    }

    @Override
    public void deleteArticleById(Long id) throws ServiceException {
        Article article = findArticleById(id);
        if (article==null){
            throw new ServiceException(ResultCode.Article_NOT_EXIST);
        }
        articleDao.deleteById(id);
    }

    //管理员审核资讯
    @Override
    public void updateArticleStatus(Long id, String status) throws ServiceException {
        Article article =findArticleById(id);
        if (article==null){
            throw new ServiceException(ResultCode.Article_NOT_EXIST);
        }
        article.setStatus(status);
        articleDao.save(article);
    }

    //根据资讯id查找资讯的所有评论，并分页显示评论
    @Override
    public Page<Comment> findAllCommentsByArticleId(Long articleId, int pageNum, int pageSize) throws ServiceException {
        PageRequest pageRequest = PageRequest.of(pageNum, pageSize);
        return commentDao.findByArticleId(articleId,pageRequest);
    }

    @Override
    public Article findArticleById(Long id) throws ServiceException {
        return articleDao.findById(id).orElse(null);
    }
}
